package com.xd.guessmusic.util;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * 音乐播放类
 * Created by Administrator on 2015/6/11.
 */
public class MyPlayer {

    /**
     * 确定的音效
     */
    public final static int INDEX_SOUND_ENTER = 0;

    /**
     * 取消的音效
     */
    public final static int INDEX_SOUND_CANCEL = 1;

    /**
     * 金币的音效
     */
    public final static int INDEX_SOUND_COIN = 2;

    /**
     * 音效文件
     */
    private final static String[] SOUND_NAMES =
            {"enter.mp3", "cancel.mp3", "coin.mp3"};

    /**
     * 音效播放器
     */
    private static MediaPlayer[] soundMediaPlayers = new MediaPlayer[SOUND_NAMES.length];

    /**
     * 单例模式
     */
    private static MediaPlayer mediaPlayer;

    /**
     * 播放声音
     * @param context
     * @param fileName
     */
    public static void playSong(Context context, String fileName){
        if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
        }
        //非第一次播放时，强制重置
        mediaPlayer.reset();

        //加载声音文件
        AssetManager assetManager = context.getAssets();
        try {
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);

            mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(), fileDescriptor.getLength());

            mediaPlayer.prepare();

            //声音播放
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止播放
     * @param context
     */
    public static void stopSong(Context context){
        if (mediaPlayer != null){
            mediaPlayer.stop();
        }
    }

    /**
     * 播放音效
     * @param context
     * @param soundIndex
     */
    public static void playSound(Context context, int soundIndex){
        if (soundMediaPlayers[soundIndex] == null){
            soundMediaPlayers[soundIndex] = new MediaPlayer();

            AssetManager assetManager = context.getAssets();
            try {
                AssetFileDescriptor fileDescriptor = assetManager.openFd(SOUND_NAMES[soundIndex]);

                soundMediaPlayers[soundIndex].setDataSource(fileDescriptor.getFileDescriptor(),
                        fileDescriptor.getStartOffset(),
                        fileDescriptor.getLength());

                soundMediaPlayers[soundIndex].prepare();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        soundMediaPlayers[soundIndex].start();
    }
}
